import util from '@/lib/util.js'
import axios from 'axios';
/**
 * 是否是微信
 *
 * @export
 * @returns
 */
export function isWechat() {
  const ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i)) {
    if (ua.match(/MicroMessenger/i)[0] === 'micromessenger') {
      return true;
    }
  }
  return false;
}

/**
 * 获取签名，并配置jsapi权限
 *
 * @export
 * @param {any} url
 */
export function wechatConfig(url) {
  let newurl = encodeURIComponent(url);
  util.ajax.get(`/wx/share/config?url=${newurl}`).then((res) => {
    if (res && res.code == '1' && res.data) {
      wx.config({
        debug: false,
        appId: res.data.app_id,
        timestamp: res.data.timestamp,
        nonceStr: res.data.nonce_str,
        signature: res.data.signature,
        jsApiList: [
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'onMenuShareQQ',
          'onMenuShareWeibo',
          'onMenuShareQZone',
          'chooseWXPay'
        ]
      });
      wx.error(function(res){
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        console.log(res);
      });
    }
  });
}

/**
 * 设置分享内容
 *
 * @export
 * @param {any} shareData
 */
export function wechatSetMethod(configData) {
  const config = {};
  if (configData.sharetitle) config.title = configData.sharetitle;
  if (configData.desc) config.desc = configData.desc;
  if (configData.link) config.link = configData.link;
  if (configData.imgUrl) config.imgUrl = configData.imgUrl;
  if (configData.complete) config.complete = configData.complete;
  const defaultConfig = {
    title: '权威专家面对面,房产动态早知道。',
    desc: '你信任的房产专家都在这里，快来关注最具价值的房产信息。',
    link: window.location.href.split('#')[0],
    imgUrl: `http://image-test.davfang.com/saas/id/2018/07/05/71ca43a2-ead6-4595-b225-b36f60a7662d.png`
  };
  const shareData = Object.assign({}, defaultConfig, config);

  wx.onMenuShareAppMessage(shareData);
  wx.onMenuShareTimeline(shareData);
  wx.onMenuShareQQ(shareData);
  wx.onMenuShareWeibo(shareData);
  wx.onMenuShareQZone(shareData);
}

/**
 * 微信配置初始分享
 *
 * @export
 * @param {any} shareTitle
 * @param {any} shareDesc
 * @param {any} shareUrl
 * @param {any} imgquan'xianPic
 */
export function wechatReady({title, desc, link, imgUrl}) {
  wx.ready(() => {
    wechatSetMethod({title, desc, link, imgUrl});
  });
}

export default {
  isWechat,
  wechatConfig,
  wechatReady,
  wechatSetMethod
};
